var Login = function () {

    var handleLogin = function() {
        $('.login-form').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                rules: {
                    username: {
                        required: true
                    },
                    password: {
                        required: true
                    },
                    remember: {
                        required: false
                    }
                },

                messages: {
                    username: {
                        required: "用户名必须填写."
                    },
                    password: {
                        required: "密码必须填写."
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit   
                    $('.alert-danger', $('.login-form')).show();
                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    label.closest('.form-group').removeClass('has-error');
                    label.remove();
                },

                errorPlacement: function (error, element) {
                    error.insertAfter(element.closest('.input-icon'));
                },

                submitHandler: function (form) {
                    // form.submit();
                    //使用AJAX提交
                    var options = {  
                        target: '#tips',          //把服务器返回的内容放入id为output的元素中      
                        // beforeSubmit: showRequest,  //提交前的回调函数  
                        success: check,      //提交后的回调函数  
                        //url: url,                 //默认是form的action， 如果申明，则会覆盖  
                        type: 'post',               //默认是form的method（get or post），如果申明，则会覆盖  
                        dataType: "json",           //html(默认), xml, script, json...接受服务端返回的类型  
                        //clearForm: true,          //成功提交后，清除所有表单元素的值  
                        //resetForm: true,          //成功提交后，重置所有表单元素的值  
                        timeout: 3000               //限制请求的时间，当请求大于3秒后，跳出请求  
                    }
                    function check(result){
                        if(result.status){
                            //登录成功后进行跳转
                            location.href=result.url;
                        }else{
                            //登录失败则进行提示
                            $('span#tips').html(result.info);
                            $('.alert-danger', $('.login-form')).show();
                        }
                    }
                    $(form).ajaxSubmit(options);
                }
            });

            $('.login-form input').keypress(function (e) {
                if (e.which == 13) {
                    if ($('.login-form').validate().form()) {
                        $('.login-form').submit();
                    }
                    return false;
                }
            });
    }

    var handleForgetPassword = function () {
        $('.forget-form').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",
                rules: {
                    email: {
                        required: true,
                        email: true
                    }
                },

                messages: {
                    email: {
                        required: "请填写直爽的邮件地址."
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit   

                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    label.closest('.form-group').removeClass('has-error');
                    label.remove();
                },

                errorPlacement: function (error, element) {
                    error.insertAfter(element.closest('.input-icon'));
                },

                submitHandler: function (form) {
                    form.submit();
                }
            });

            $('.forget-form input').keypress(function (e) {
                if (e.which == 13) {
                    if ($('.forget-form').validate().form()) {
                        $('.forget-form').submit();
                    }
                    return false;
                }
            });

            jQuery('#forget-password').click(function () {
                jQuery('.login-form').hide();
                jQuery('.forget-form').show();
                jQuery("input[name='email']").focus();
            });

            jQuery('#back-btn').click(function () {
                jQuery('.login-form').show();
                jQuery('.forget-form').hide();
                jQuery("input[name='username']").focus();
            });

    }

    var handleRegister = function () {

        function format(state) {
            if (!state.id) return state.text; // optgroup
            return "<img class='flag' src='../../assets/global/img/flags/" + state.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + state.text;
        }


        $("#select2_sample4").select2({
            placeholder: '<i class="fa fa-map-marker"></i>&nbsp;Select a Country',
            allowClear: true,
            formatResult: format,
            formatSelection: format,
            escapeMarkup: function (m) {
                return m;
            }
        });


            $('#select2_sample4').change(function () {
                $('.register-form').validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
            });



         $('.register-form').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",
                rules: {
                    
                    fullname: {
                        required: true
                    },
                    email: {
                        required: true,
                        email: true
                    },
                    address: {
                        required: true
                    },
                    city: {
                        required: true
                    },
                    country: {
                        required: true
                    },

                    username: {
                        required: true
                    },
                    password: {
                        required: true
                    },
                    rpassword: {
                        equalTo: "#register_password"
                    },

                    tnc: {
                        required: true
                    }
                },

                messages: { // custom messages for radio buttons and checkboxes
                    tnc: {
                        required: "您必须同意用户协议."
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit   

                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    label.closest('.form-group').removeClass('has-error');
                    label.remove();
                },

                errorPlacement: function (error, element) {
                    if (element.attr("name") == "tnc") { // insert checkbox errors after the container                  
                        error.insertAfter($('#register_tnc_error'));
                    } else if (element.closest('.input-icon').size() === 1) {
                        error.insertAfter(element.closest('.input-icon'));
                    } else {
                        error.insertAfter(element);
                    }
                },

                submitHandler: function (form) {
                    form.submit();
                }
            });

            $('.register-form input').keypress(function (e) {
                if (e.which == 13) {
                    if ($('.register-form').validate().form()) {
                        $('.register-form').submit();
                    }
                    return false;
                }
            });

            jQuery('#register-btn').click(function () {
                jQuery('.login-form').hide();
                jQuery('.register-form').show();
                jQuery("input[name='username-reg']").focus();
            });

            jQuery('#register-back-btn').click(function () {
                jQuery('.login-form').show();
                jQuery('.register-form').hide();
                jQuery("input[name='username']").focus();
            });
    }
    
    return {
        //main function to initiate the module
        init: function () {
            
            handleLogin();
            handleForgetPassword();
            handleRegister();    
        },
        showLogin:function(){
            jQuery('.login-form').show();
            jQuery('.forget-form').hide();
            jQuery('.register-form').hide();
            jQuery("input[name='username']").focus();
        },
        showForget:function(){
            jQuery('.login-form').hide();
            jQuery('.forget-form').show();
            jQuery('.register-form').hide();
            jQuery("input[name='email']").focus();
        },
        showRegister:function(){
            jQuery('.login-form').hide();
            jQuery('.forget-form').hide();
            jQuery('.register-form').show();
            jQuery("input[name='username-reg']").focus();
        }

    };

}();